package com.paiai.lslease.service.appuser;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dsmzg.base.util.DateTools;
import com.paiai.lslease.auto.dao.AppHouseDAO;
import com.paiai.lslease.auto.dao.AppLockDAO;
import com.paiai.lslease.auto.dao.AppLockOpenrecordDAO;
import com.paiai.lslease.auto.dao.AppSysUserDAO;
import com.paiai.lslease.auto.dao.AppSysUserRoleDAO;
import com.paiai.lslease.auto.model.AppHouse;
import com.paiai.lslease.auto.model.AppLock;
import com.paiai.lslease.auto.model.AppLockExample;
import com.paiai.lslease.auto.model.AppLockOpenrecord;
import com.paiai.lslease.auto.model.AppSysUser;
import com.paiai.lslease.auto.model.AppSysUserExample;
import com.paiai.lslease.auto.model.AppSysUserRole;
import com.paiai.lslease.auto.model.AppSysUserRoleExample;
import com.paiai.lslease.base.AppResult;
import com.paiai.lslease.dao.doorrecord.OpenDoorDao;
import com.paiai.lslease.enums.OpenDoorType;
import com.paiai.lslease.model.bo.query.AppLockOpenrecordQuery;
import com.paiai.lslease.model.bo.query.AppUserLockInfoQuery;
import com.paiai.lslease.model.vo.OpenDoorRecordVo;

/** 
* @author chenmfa
* @version 创建时间：2017年10月20日 上午11:14:39 
* @description
*/
@Service("appOpenRecordService")
public class AppOpenRecordServiceImpl implements AppOpenRecordService{
  @Autowired
  AppLockDAO appLockDAO;
  @Autowired
  AppSysUserDAO appSysUserDAO;
  @Autowired
  AppLockOpenrecordDAO appLockOpenrecordDAO;
  @Autowired
  AppSysUserRoleDAO appSysUserRoleDAO;
  @Autowired
  OpenDoorDao openDoorDao;
  @Autowired
  AppHouseDAO appHouseDAO;
  /**
   * @description 添加用户开门记录
   * @param record
   * @param mac
   * @throws SQLException
   */
  public void addOpenDoorRecord(AppLockOpenrecord record, String mac) throws SQLException{
    Date da = new Date();
    record.setInsertTime(da);
    record.setOpenType(1);
    record.setOpenTime(da);
    record.setUpdateTime(da);
    //查询用户信息
    AppSysUser user = queryUserInfo(record.getOpenIdentify());
    if(null != user){
      record.setUserId(user.getId());
    }else{
      record.setUserId(0);
    }
    AppLock lock = queryAppLockInfo(mac);
    if(null != lock){
      record.setLockId(lock.getId());
    }else{
      record.setLockId(0);
      record.setItem1(mac);
    }
    appLockOpenrecordDAO.insertSelective(record);
  }
  
  /**
   * @description 查询用户开门记录
   * @throws SQLException
   */
  public AppResult queryOpenDoorRecord(AppLockOpenrecordQuery query) throws SQLException{
    AppResult result;
    Map<String,AppSysUser> userMap = new HashMap<String,AppSysUser>();
    //查询用户角色
    AppSysUser userInfo = queryUserInfoFromCache(query.getMobile(), userMap);
    if(null == userInfo){
      result = AppResult.newFailResult("用户信息不存在");
    }else{
      //查询用户角色
      List<AppSysUserRole> roleList = queryUserRoleList(userInfo.getId());
      boolean match = false;
      if(null != roleList && roleList.size() > 0){        
        for(AppSysUserRole role :roleList){
          if(null != role.getRoleId() && (role.getRoleId() == 10029 || role.getRoleId() == 10030)){
            match = true;
            break;
          }
        }
      }
      if(!match){        
        result = AppResult.newFailResult("非房东暂时不能查询开门记录");
      }else{
        //查询用户的设备列表
        AppUserLockInfoQuery userLockQuery = new AppUserLockInfoQuery();
        userLockQuery.setTenantFlag(null);
        userLockQuery.setUserId(userInfo.getId());
        String lockIdList =  openDoorDao.queryUserLockList(userLockQuery);
        query.setLockIdList(lockIdList);
        //如果是查询特定mac地址的,则传入当前用户的mac
        Map<Integer, AppLock> lockMap = new HashMap<Integer,AppLock>();
        if(null != query.getMac()){
          AppLock lockInfo = queryAppLockInfo(query.getMac());
          if(null == lockInfo){
            result = AppResult.newFailResult("查询的设备信息不存在");
            return result;
          }
          lockMap.put(lockInfo.getId(), lockInfo);
        }
        //开始查询开门记录
        List<AppLockOpenrecord> recordList = openDoorDao.queryOpenDoorRecord(query);
        List<OpenDoorRecordVo> voList = new ArrayList<OpenDoorRecordVo>();
        if(null != recordList && recordList.size()>0){
          for(AppLockOpenrecord record:recordList){           
            OpenDoorRecordVo vo = new OpenDoorRecordVo();
            vo.setOpenTime(DateTools.commonformatter.format(record.getOpenTime()));
            //查询缓存用户信息并设置昵称
            switch(record.getOpenType()){
              case 1:
              case 2:
                AppSysUser user = queryUserInfoFromCache(record.getOpenIdentify(), userMap);
                if(null != user){
                  vo.setNickName(user.getNickName());
                  vo.setPhoto(user.getPhoto());
                }else{
                  vo.setPhoto("");
                  vo.setNickName("");
                }
                break;
              case 4:
                vo.setNickName(OpenDoorType.PASSWORD.toString());
                break;
              default:
                vo.setNickName(OpenDoorType.UNKNOWN.toString());
                break;
            }
            vo.setOpenType(record.getOpenType());
            //查询房源信息并设置名称和地址            
            AppLock lock = queryLockInfoFromCache(record.getLockId(), lockMap);
            if(null != lock){
              vo.setLockName(lock.getName());
              Map<Integer, AppHouse> houseMap = new HashMap<Integer,AppHouse>();
              AppHouse house = queryLockHouseInfoFromCache(lock.getHouseId(), houseMap);
              if(null != house){
                vo.setHouseAddress(house.getHouseAddress());
                vo.setHouseName(house.getHouseName());
              }else{
                vo.setHouseAddress("");
                vo.setHouseName("");
              }
            }else{
              vo.setLockName("未注册设备");
              vo.setHouseAddress("");
              vo.setHouseName("");
            }
            voList.add(vo);
          }
        }
        result = AppResult.newSusscessResult(voList);
      }
    }
    return result;
  }
  
  private AppSysUser queryUserInfoFromCache(String mobile,Map<String,AppSysUser> map) throws SQLException{
    if(map.containsKey(mobile)){
      return map.get(mobile);
    }else{
      map.put(mobile, queryUserInfo(mobile));
      return map.get(mobile);
    }
  }
  
  private AppLock queryLockInfoFromCache(Integer lockId,Map<Integer,AppLock> lockMap) throws SQLException{
    if(lockMap.containsKey(lockId)){
      return lockMap.get(lockId);
    }else{
      lockMap.put(lockId, queryAppLockInfo(lockId));
      return lockMap.get(lockId);
    }
  }
  
  private AppHouse queryLockHouseInfoFromCache(Integer houseId, Map<Integer,AppHouse> houseMap) throws SQLException{
    if(houseMap.containsKey(houseId)){
      return houseMap.get(houseId);
    }else{
      houseMap.put(houseId, queryAppHouseInfo(houseId));
      return houseMap.get(houseId);
    }
  }
  
  private AppSysUser queryUserInfo(String mobile) throws SQLException{
    //查询用户信息
    AppSysUserExample userEx = new AppSysUserExample();
    userEx.createCriteria().andMobileEqualTo(mobile);
    List<AppSysUser> userList = appSysUserDAO.selectByExample(userEx);
    return (null == userList || userList.size() == 0)?null:userList.get(0);
  }
  
  private AppLock queryAppLockInfo(String mac) throws SQLException{
    AppLockExample example = new AppLockExample();
    example.createCriteria().andMacAddressEqualTo(mac);
    List<AppLock> list = appLockDAO.selectByExample(example);
    return (null == list || list.size() == 0)?null:list.get(0);
  }
  
  private AppLock queryAppLockInfo(Integer lockId) throws SQLException{
    return appLockDAO.selectByPrimaryKey(lockId);
  }
  
  private AppHouse queryAppHouseInfo(Integer houseId) throws SQLException{
    return appHouseDAO.selectByPrimaryKey(houseId);
  }
  
  private List<AppSysUserRole> queryUserRoleList(Integer userId) throws SQLException{
    AppSysUserRoleExample example = new AppSysUserRoleExample();
    example.createCriteria().andUserIdEqualTo(userId);
    return appSysUserRoleDAO.selectByExample(example);
  }
}
